package com.kubepartners.impactmodel.translator.graphml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.kubepartners.impactmodel.model.Edge;
import com.kubepartners.impactmodel.model.Graph;
import com.kubepartners.impactmodel.model.Node;
import com.kubepartners.impactmodel.translator.GraphReader;

public class GraphmlResultsReader extends DefaultHandler implements GraphReader {
	// default graph
	private Graph graph = new Graph(Edge.class);
	
	// default parameter Map
	private Map map = new HashMap();

	// state engine
	private boolean inGraphml = false;
	private boolean inGraph = false;
	private boolean inNode = false;
	private boolean inData = false;
	private Node currentNode = null;
	private String currentString = "";
	private boolean inInduced = false;
	private boolean inDelivered = false;;

	// Parser calls this for each element in a document
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {
		if (localName.equals("graphml")) {
			inGraphml = true;
		}
		if (localName.equals("graph")) {
			if (inGraphml) {
				inGraph = true;
			}
		}
		if (localName.equals("node")) {
			if (inGraph) {
				inNode = true;
				currentNode = graph.findNodeByLabel(atts.getValue("id"));
			}
		}
		if (localName.equals("data")) {
			inData = true;
			if (atts.getValue("key").equals("d6")) {
				inInduced = true;
			}
			if (atts.getValue("key").equals("d7")) {
				inDelivered = true;
			}
		}
	}

	public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
		if (localName.equals("graphml")) {
			inGraphml = false;
		}
		if (localName.equals("graph")) {
			inGraph = false;
		}
		if (localName.equals("node")) {
			inNode = false;
			currentNode = null;
		}
		if (localName.equals("data")) {
			if (currentString.length() > 0) {
				// Check for Node data
				if (inNode && inData && currentNode != null) {
					if (inInduced) {
						currentNode.setInducedCapacity(Double.parseDouble(currentString));
					}
					if (inDelivered) {
						currentNode.setDeliveredCapacity(Double.parseDouble(currentString));
					}
				}
				// Reset state
				inData = false;
				inInduced = false;
				inDelivered = false;
				currentString = "";
			}
		}
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		currentString = currentString + String.valueOf(ch, start, length).trim();
	}

	public Graph readGraph(InputStream is) {
		// TODO Auto-generated method stub
		return graph;
	}

	public void setGraph(Graph graph) {
		this.graph = graph;		
	}

}
